package com.itheima.reggie.service.impl;

import com.itheima.reggie.entity.User;
import com.itheima.reggie.exception.BusinessException;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired(required = false)
    private UserMapper userMapper;

    /**
     * 用户登录的方法
     *
     * @param phone       手机号
     * @param UserCode    用户输入的验证码
     * @param SessionCode 后端生成的验证码
     * @return User
     */
    @Override
    public User login(String phone, String UserCode, String SessionCode) {
        //1.传递过来手机号,用户输入验证码和session的验证码
        //2.校验验证码是否正确,如果不正确返回"验证码错误"
        if (!UserCode.equals(SessionCode)) {
            throw new BusinessException("验证码错误");
        }

        //3.根据手机号查找用户对象,判断是否禁用,如果找到并没有禁用直接返回
        User loginUser = userMapper.findByPhone(phone);
        if (loginUser != null) {
            if (loginUser.getStatus() == 1) {
                //status=1说明用户被禁用了
                throw new BusinessException("您的手机号已被禁用");
            }
        } else {
            //4.如果找不到,完善用户数据(设置状态为1正常),并添加用户到数据库
            //封装手机号状态
            User user = new User();
            user.setStatus(0);
            user.setPhone(phone);

            userMapper.save(user);

        }
        //5.返回用户登录用户对象
        return loginUser;
    }
}